const mongoose = require('mongoose')
const uuidv4 = require('uuid/v4')
mongoose.Promise = global.Promise

const UserSchema = new mongoose.Schema({
  uuid: {type: String, default: uuidv4()},
  username: {type: String, required: true, unique: true},
  password: {type: String, required: true},
  tel: Number,
  registerIP: String,
  registerTime: { type: Date, default: Date.now() },
  loginIP: String,
  loginTime: Date,
  meta: {
    createAt: { type: Date, default: Date.now() },
    updateAt: { type: Date, default: Date.now() }
  }
})

UserSchema.pre('save', function (next) {
  if (!this.isNew) {
    this.registerAt = Date.now()
    this.meta.createAt = this.meta.updateAt = Date.now()
  }
  next()
})

UserSchema.statics = {
  fetch (cb) {
    this.find({}).exec(cb)
  },
  findByUsername (name, cb) {
    this.findOne({username: name}).exec(cb)
  }
}

module.exports = UserSchema
